<?php

/**
* @TODO Remake inorder to decrease SQL-queries quantity. 
* 
*/
class Resource_Backend_Action_Common_Delete extends Backend_Component_Delete 
{
    
    /**
    * @desc Define whether parent element is needed.
    * 
    * @param boolean
    */
    protected $_parent;
    
    /**
    * Navigation name. 
    * 
    * @param string
    */
    public $navigation; 
    
    /**
     * @desc Start filter.
     *
     */
    public function process() 
    {
        // check for menu name
        if (is_null($this->navigation)) {
            trigger_error('Menu name must be specified', E_USER_ERROR);
        }
        // check parent presance
        if (is_null($this->_parent)) {
            trigger_error('Parent prasence must be specified', E_USER_ERROR);
        }
        
        parent::process();
    }
    
    /**
     * @desc Gather data of all the items.
     *
     * @return  boolean
     */
    protected function _delete() 
    {
        $id = (int)Application::getRequest()->get('id');
        $id_list = array($id);
        
        // in case of parent presence gather children
        if ($this->_parent) {
            $entries = Kernel::factory('Kernel', 'Resource')->menu($this->navigation);
            $this->_childrenRecursive(Kernel_Util_Tree::children($entries, $id), $id_list);
        }
        
        $query = '
            SELECT 
                   `r`.`id`, 
                   `r`.`name`, 
                   `r`.`module`, 
                   `r`.`url`, 
                   `i`.`parent_id` `parent`
              FROM 
                   `system_resource` `r`, 
                   `system_navigation_item` `i`
             WHERE 
                   `i`.`resource_id` = `r`.`id`
               AND
                   ' . database::condition(array('`r`.`id`' => $id_list)) . '
          ORDER BY 
                   `r`.`id` 
              DESC
            ';
        
        try {
            foreach (database::fetchAll($query) as $item) {
               $this->_deleteAll($item);
            }
        } catch (Resource_Backend_Exception $e) {
            Application::getResponse()->message(false, $e->getMessage());
            $this->_location(Application::getRequest()->referer() 
                ? Application::getRequest()->referer()
                : $this->back);
        }
        
        return true;
    }
    
    /**
    * Delete every item manually.
    * 
    */
    private function _deleteAll($item) 
    {
        extract($item);
        
        // check for correct resource
        if (!in_array($module, array_keys($this->_avaliableModules()))) {
            throw new Resource_Backend_Exception(__('RESOURCE_DELETED_ERROR', $name, $module));
        }
        
        $params = array(
            'table' => 'system_navigation_item', 
            'id_field' => 'resource_id', 
            'condition' => array('menu_id' => Resource_Backend_Utils::menuId($this->navigation))
            );
        if ($this->_parent) {
            $params['parent'] = $parent;
        }
        
        $affected_rows = Kernel::factory('Kernel_Form', 'Order', $params)
            ->deleteNode($id);
            
        if ($affected_rows) {
            database::delete('system_resource', $id);
        }
    }
    
    private function _childrenRecursive($set, &$list) 
    {
        foreach ($set as $node) {
            array_push($list, (int)$node['id']);
            if (!empty($node['children'])) {
                $this->_childrenRecursive($node['children'], &$list);
            }
        }
    }
    
    protected function _avaliableModules() 
    {
        return Resource_Backend_Utils::availableModules();
    }
    
}